package com.qk.pckeyspringboot.control;

import com.qk.pckeyspringboot.server.JsonFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/")
public class JsonFileController {

    @Autowired
    public JsonFileService jsonFileService;

    @Autowired
    private ApplicationContext applicationContext;

    //读取json文件
    @GetMapping("/readJsonFile")
    public String readJsonFile() {
        return jsonFileService.readJsonFile();
    }

    //写入json文件
    @PostMapping("/writeJsonFile")
    public String writeJsonFile(@RequestBody String json) {
        return jsonFileService.writeJsonFile(json);
    }

    @PostMapping("/uploadJsonFile")
    public String uploadJsonFile(@RequestBody MultipartFile file) {
        String json = "";
        try {
            json = new String(file.getBytes(), StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(json);
        return json;
    }

    // 新增的Windows停止服务接口
    @PostMapping("/shutdown")
    public String shutdown() {
        new Thread(() -> {
            try {
                // 等待1秒确保响应能返回
                Thread.sleep(1000);

                // 停止Spring Boot应用
                SpringApplication.exit(applicationContext, () -> 0);

                // 停止Nginx (Windows专用命令)
                Runtime.getRuntime().exec("taskkill /F /IM nginx.exe");

            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();

        return "1秒后停止服务";
    }
}